package com.example.yue.appclent;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yue.appclent.client.ClientRunable;
import com.example.yue.appclent.client.Contast;
import com.example.yue.appclent.client.TvLog;
import com.example.yue.appclent.client.bean.ClientMessBean;
import com.example.yue.appclent.client.bean.ServerMessBean;
import com.example.yue.appclent.contast.MessFlag;
import com.example.yue.appclent.util.JsonUtil;
import com.lu.sn.Language;
import com.lu.sn.NameType;
import com.lu.sn.RandomNameTool;

import java.util.Random;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText etIpTextMain;
    private EditText etPortTextMain;
    private EditText etSendTextMain;
    private Button btnSendMessMain;
    private ClientRunable clientRunable;
    private Handler handler;
    private TextView tvLogMain;

    private static String IP = "192.168.1.195";
    private static int PORT = 2537;
    private Button btnLinkMain;
    private TvLog tvLog;
    private EditText etNameTextMaint;
    private Button btnSendCmdMain;

    private void assignViews() {
        etNameTextMaint = (EditText) findViewById(R.id.et_nameText_main);
        etIpTextMain = (EditText) findViewById(R.id.et_ipText_main);
        etPortTextMain = (EditText) findViewById(R.id.et_portText_main);
        etSendTextMain = (EditText) findViewById(R.id.et_sendText_main);
        btnSendMessMain = (Button) findViewById(R.id.btn_sendMess_main);
        btnLinkMain = (Button) findViewById(R.id.btn_link_main);
        btnSendCmdMain = (Button) findViewById(R.id.btn_sendCmd_main);
        tvLogMain = (TextView) findViewById(R.id.tv_log_main);


        Random random = new Random();
        int next = random.nextInt(2);
        if (next == 0){
            etNameTextMaint.setText(RandomNameTool.getName(Language.en, NameType.FULL_NAME));
        }else {
            String bianma = null;
            etNameTextMaint.setText(RandomNameTool.getName(Language.zh, NameType.FULL_NAME));
        }

        etIpTextMain.setText(IP);
        etPortTextMain.setText(PORT + "");

        btnLinkMain.setOnClickListener(this);
        btnSendMessMain.setOnClickListener(this);
        btnSendCmdMain.setOnClickListener(this);

        tvLog = TvLog.newInstance(tvLogMain, 10);

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        assignViews();
    }

    public void initClient(String host, int port) {

        if (handler == null) {
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    // 如果消息来自子线程
                    if (msg.what == Contast.MESS_FROM_RUN) {
                        // 读取来自服务器的json
                        String jsonStr = msg.obj.toString();
                        ServerMessBean serverMessBean = JsonUtil.getServerMessBean(jsonStr);

                        if (serverMessBean != null) {

                            int flag = serverMessBean.getMessFlag();
                            if (flag == MessFlag.FLAG_MAIN) {
                                String name = serverMessBean.getName();
                                String content = serverMessBean.getMess();
                                String logText = name + "：" + content;
                                tvLog.log("\n"+logText);

                                //如果服务器下达了命令
                            } else if (flag == MessFlag.FLAG_CMD) {
                                String cmd = serverMessBean.getCmdMess();
                                if ("exit".equals(cmd)) {
                                    finish();
                                } else if ("toast".equals(cmd)) {//接受服务器命令弹出toast
                                    Toast.makeText(MainActivity.this, serverMessBean.getOtherMess(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        }

                        Log.d(">>>", jsonStr);
                    }
                }
            };
        }
        if (clientRunable == null) {
            clientRunable = new ClientRunable(handler, host, port);
            new Thread(clientRunable).start();
        }
    }

    /**
     * 改变端口，ip暂时无效
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_link_main:
                linkServe();
                break;
            case R.id.btn_sendMess_main:
                sendMess();
                break;
            case R.id.btn_sendCmd_main:
                sendCmd();
                break;
        }
    }

    /**
     * 发送命令
     */
    private void sendCmd() {
        sendText(MessFlag.FLAG_CMD, "悄悄地打它，它应该不知道");
    }

    private void sendMess() {
        sendText(MessFlag.FLAG_MAIN, "悄悄地骂服务器，它应该不知道");
    }

    private void linkServe() {

        String ipText = etIpTextMain.getText().toString();
        String portText = etPortTextMain.getText().toString();

        if (StringRegex.isNumber(portText) && StringRegex.isIp4(ipText)) {
            int port = Integer.parseInt(portText);
            if (clientRunable != null) {
                clientRunable.close();
                clientRunable = null;
            }
            initClient(ipText, port);
        } else {
            Toast.makeText(this, "非法的输入", Toast.LENGTH_SHORT).show();
        }
    }

    private void sendText(int messFlag, String otherMess) {

        if (clientRunable != null) {
            String name = etNameTextMaint.getText().toString();
            String content = etSendTextMain.getText().toString();

            String logText = name + "：" + content;

            ClientMessBean clientMessBean = new ClientMessBean(System.currentTimeMillis(), name, null, content, messFlag, otherMess);
            String sendJson = JsonUtil.getJsonString(clientMessBean);

            Message msg = new Message();
            msg.what = Contast.MESS_FROM_UI;
            msg.obj = sendJson;

            clientRunable.sendMess(msg);
            etSendTextMain.setText("");

            tvLog.log("\n"+logText);
        } else {
            tvLog.log("\n连接失效或未连接");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (clientRunable != null) {
            clientRunable.close();
        }
    }
}
